//
//  WBStatusViewModel.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/6.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit

class WBStatusViewModel: NSObject {
    //拥有模型数据类
    var status:WBStatus?
    
    
    //设置微博返回数据是否是转发 进行拼接
    var reposts_String: String? {
        //实现模型判断
        return status?.reposts_count == 0 ? ("转发"):(dealCount(status?.reposts_count))
    }
    
    //---------------判断点赞-------------
    var goods_String:String? {
        
        return status?.attitudes_count == 0 ?("点赞"):(dealCount(status?.attitudes_count))
    }
    
    
    //-----------------评论判断-----------
    var comments_String:String? {
        
        return status?.comments_count == 0 ?("评论"):(dealCount(status?.comments_count))
    }
    
    //-----------------等级返回图片--------------
    var levelImage:UIImage? {
        if  status?.user?.mbrank >= 1 && status?.user?.mbrank >= 7 {
            return UIImage(named:"common_icon_membership_level\(status?.user?.mbrank ?? 0)")
        }
        return UIImage()//(named: "")
    }
    
    
    
    //----------------判断是否是认证用户-----------
    var verifityImage:UIImage? {
        
        guard let type = status?.user?.verified_type else {
            return  UIImage()//(named: "")
        }
        
        switch type {
        case -1: return UIImage()//(named: "")
        case 0: return UIImage(named: "avatar_vip")
        case 1,2,3,5: return UIImage(named: "avatar_enterprise_vip")
        case 220: return UIImage(named: "avatar_grassroot")
            
            //Swith中必须加入
        default :return UIImage()//UIImage(named: "")
        }
    }
    
    //_____________________返回头像_________________
    
    //头像转换成URL
    var profile_url: NSURL? {
        
        if  let url = status?.user?.profile_image_url {
            
            return  NSURL(string: url)
            
        }else {
            return NSURL(string: "")
            
        }
        
    }
    
    
    
    
    //--------------------转发微博信息==================
    var retweeted_String: String? {
        
        return status?.retweeted_status?.text
        
    }
    
    
    //------------转发微博的配图视图---------------
    var retweet_pic_urls: [WBPhotoViewModel]? {
        
        return status?.retweeted_status?.pic_urls
        
    }
    
    
    //来源字符串
    var source_string: String? {
        
        return dealSource(status?.source)
    }
    
    
    //时间显示字符串
    var createat_string: String? {
        return dealCreateTime(status?.created_at)
    }
    
    
    //初始化模型
    init(model:WBStatus) {
        self.status = model
        
        super.init()
        
    }
    
    ///  处理转发微博的数据 逻辑
    private func dealCount(count: Int?) -> String{
        
        guard let count = count else {
            
            return ""
        }
        
        if count < 10000 {
            
            return "\(count)"
        } else {
            19.9999
            let show = Float(count) / 10000.0
            return String(format: "%.2f万", show)
            
        }
    }
    
    
    //处理 发布的时间 和来源
    private func dealSource(source: String?) ->String {
        
        //Optional("<a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a>")
        //通过截取
        guard let sourceStr = source else {
            
            return ""
        }
        
        let subsourceArray = sourceStr.componentsSeparatedByString(">")
        
        //判断一下
        if subsourceArray.count > 2 {
            let lastSubArray = subsourceArray[1].componentsSeparatedByString("<")
            
            if lastSubArray.count >= 1 {
                return lastSubArray[0]
            }
        }
        return ""
    }
    
    //====================================发布时间处理
    
    func dealCreateTime(createdate: String?) ->String {
        //把 // 第一大步： 需要把 Tue May 10 10:42:03 +0800 2016 转换成一个标准时间 yyyy-MM-dd HH:mm:ss 00000
        guard let createDate = createdate else {
            return ""
        }
        
        
        //1.
        let formate = NSDateFormatter()
        
        /*
        设置日期格式 （声明字符串里面每个数字和单词的含义）
        E：星期
        M: 月份
        d：日
        H: 24小时
        m: 分
        s: 秒
        y: 年
        Z 时区
        */
        // Tue May 10 10:42:03 +0800 2016
        formate.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        //设置时区 Asia/Beijing 北京   "zh_CN"中国 en_US
        formate.locale = NSLocale(localeIdentifier: "Asia/Beijing")
        
        //转换成标准时间
        let date = formate.dateFromString(createDate)
        print(date)
        //第二部分和 NSco
        let calnder = NSCalendar.currentCalendar()
        
        //获取枚举的单个类型
        //let unit1 = NSCalendarUnit(rawValue: 0)
        // 获取枚举的多个类型 用 (arrayLiteral:)
        /*
        public static var Era: NSCalendarUnit { get }
        public static var Year: NSCalendarUnit { get }
        public static var Month: NSCalendarUnit { get }
        public static var Day: NSCalendarUnit { get }
        public static var Hour: NSCalendarUnit { get }
        public static var Minute: NSCalendarUnit { get }
        public static var Second: NSCalendarUnit { get }
        public static var Weekday: NSCalendarUnit { get }
        public static var WeekdayOrdinal: NSCalendarUnit { get }
        */
        
        let umit = NSCalendarUnit(arrayLiteral: .Year,.Month,.Day,.Hour,.Minute)
        let cmps = calnder.components(umit, fromDate: date!, toDate: NSDate(), options: [])
        
        if cmps.year == 0 {//是今年
            if cmps.month == 0{ //是本月
                if cmps.day == 0 { //是今天
                    if cmps.hour == 0{ //下时之内
                        if cmps.minute < 1 { //刚刚
                            return "刚刚"
                            
                        }else{//1小时之内 显示 "xx分钟前"
                            return "\(cmps.minute)分之前"
                            
                        }
                        
                    }else{ //显示xx小时前
                        return "\(cmps.hour)小时前"
                    }
                    
                }else if cmps.day == 1{//是昨天
                    // "昨天 HH:mm"
                    //获取一下 发布微博的 小时:分钟
                    //FromDate(<#T##date: NSDate##NSDate#>) 这个得是一个标准时间
                    formate.dateFormat = "HH:mm"
                    let str = formate.stringFromDate(date!)
                    return "昨天\(str)"
                }else { //本月的其他月份
                    formate.dateFormat = "MM-dd HH:mm"
                    return formate.stringFromDate(date!)
                }
                
            }else { //不是本月 本月的其他月份
                
                formate.dateFormat = "MM-dd HH:mm"
                
            }
            
        }else { //不是今年
            
        }
        return ""
    
       }
    
    //图文混排显示
    func dealAttributeString(text: String?) ->NSAttributedString? {
//        let temp = "[馋嘴]测试的[馋嘴]lable"
        guard let text = text else {
           return nil
        }
        
        let tempAttribute = NSMutableAttributedString(string:text)
        //正则
        let pattern = "\\[.*?\\]"
        
        do {
    //1.创建一个正则的查找
    let regx = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
    //2.查找返回查找结果集
    let reslults = regx.matchesInString(text, options: [], range: NSMakeRange(0, text.characters.count))
    //对结果进行反向遍历
    var count = reslults.count
    //           printLog(count)
    while count > 0 {
        
        let result = reslults[--count]
        
        let emoticonStr = (text as NSString).substringWithRange(result.range)
        
        //printLog(result.range)
        //去model的数组内容中去匹配表情
        if let emoticon = WBEmoticonManager.searchEmoticon(emoticonStr){
            
    let imageAttritute = WBTextAttachment.getEmoiconAttributeString(emoticon, fontHeight: 16)
            
         //把附件的东西替换
        tempAttribute.replaceCharactersInRange(result.range, withAttributedString: imageAttritute)
      
        }
     }
            
    }catch {
            
            print(error)
        }
        
        return tempAttribute
    }
    
}
